package com.competition.prediction.service.impl;

import com.competition.prediction.dto.UserLoginDTO;
import com.competition.prediction.dto.UserRegisterDTO;
import com.competition.prediction.entity.User;
import com.competition.prediction.mapper.UserMapper;
import com.competition.prediction.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public String register(UserRegisterDTO registerDTO) {
        if (userMapper.selectUserByUsername(registerDTO.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        if (registerDTO.getEmail() != null && userMapper.selectUserByEmail(registerDTO.getEmail()) != null) {
            throw new RuntimeException("邮箱已被注册");
        }
        if (registerDTO.getPhone() != null && userMapper.selectUserByPhone(registerDTO.getPhone()) != null) {
            throw new RuntimeException("手机号已被注册");
        }

        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setCoins(1000L);
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        if (userMapper.insertUser(user) > 0) {
            return "注册成功";
        }
        throw new RuntimeException("注册失败");
    }

    @Override
    public String login(UserLoginDTO loginDTO) {
        User user = userMapper.selectUserByUsername(loginDTO.getUsername());
        if (user == null || !passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }
        return "登录成功";
    }

    @Override
    public User getUserInfo(Long userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    @Transactional
    public boolean updateUserInfo(User user) {
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.updateUser(user) > 0;
    }

    @Override
    @Transactional
    public boolean updateUserCoins(Long userId, Long coins) {
        return userMapper.updateUserCoins(userId, coins) > 0;
    }

    @Override
    public Long getUserCoins(Long userId) {
        User user = userMapper.selectUserById(userId);
        return user != null ? user.getCoins() : 0L;
    }
}